import time
import hmac
import json
import hashlib
import base64
import urllib.parse
import requests
from prometheus.prometheus import Prometheus


class Dingtalk:
    def __init__(self,webhook_url, mobiles, secret=None, msg_type="markdown"):
        self.webhook_url = webhook_url
        self.mobiles = mobiles
        self.secret = secret
        self._msg_type = msg_type
        self.url = None
        self.data = None
        self.sign = None
        self.msg_type = None
        self.timestamp = str(round(time.time() * 1000))
        self.headers = {'Content-Type': 'application/json'}

    def _sign(self):
        secret_enc = self.secret.encode('utf-8')
        string_to_sign = '{}\n{}'.format(self.timestamp, self.secret)
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        self.sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))

        self.url = self.webhook_url + '&timestamp={}'.format(self.timestamp) + '&sign={}'.format(self.sign)

    def send(self):
        self._sign()
        requests.post(url=self.url, headers=self.headers, data=self.data)

    def _data(self, data):
        self.msg_type = getattr(self, self._msg_type, None)
        if self.msg_type is None:
            raise NotSupportException("{} message type is not supported".format(self.msg_type))
        self.msg_type(data)

    def markdown(self, d):
        title = d['title']
        text = d['text']
        data = json.dumps({
            "msgtype": "markdown",
            "markdown": {
                "title": title,
                "text": text
            },
            "at": {
                "atMobiles": self.mobiles,
                "isAtAll": False
            }
        })
        self.data = data

    def text(self):
        # TODO
        pass

    def link(self):
        # TODO
        pass

    def actioncard(self):
        # TODO
        pass

    def feedcard(self):
        # TODO
        pass


class NotSupportException(Exception):
    def __init__(self, msg):
        self.msg = msg